﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CompactFramework.Utilities.Localization;

namespace TripLOAMobile
{
    public partial class ShowMessageBox : LocalizedForm
    {
        WS_SoapMessage.Message[] messages;

        private AnimationControl animation;

        #region Initialization
        /// <summary>
        /// Initializes a new instance of the ShowMessageBox class.
        /// </summary>
        public ShowMessageBox()
        {
            #region creation of the control for the animation
            animation = new AnimationControl();
            int x = this.Width / 2 - animation.Width / 2;
            int y = this.Height / 2 - animation.Height / 2;
            animation.Location = new Point(x, y);
            this.Controls.Add(animation);
            animation.BringToFront();
            #endregion
            InitializeComponent();
            this.AddMenusToDictionary();
            UpdateResources();
            comboMessage.Items.Add(ResourceManager.Instance.GetString("UnreadMessages"));
            comboMessage.Items.Add(ResourceManager.Instance.GetString("AllMessages"));
            this.fldText.ScrollBars = ScrollBars.Vertical;
            comboMessage.SelectedIndex = 0;
            if (Welcome.formBuffer.GetFormNames().Contains("ShowProfileInfo"))
                menuItem4.Enabled = true;
            else menuItem4.Enabled = false;
        }

        /// <summary>
        /// Initializes the informations showed in the form.
        /// </summary>
        /// <param name="m">The array of messages.</param>
        private void InitializeInformations(WS_SoapMessage.Message[] m)
        {
            listMessages.Items.Clear();
            messages = m;
            int index = 0;
            foreach (WS_SoapMessage.Message message in messages)
            {
                listMessages.Items.Add(message.Sender + " : " + message.Title);
                index++;
            }
            listMessages.SelectedIndex = (index == 0) ? -1 : 0;
            menuItemReply.Enabled = index != 0;
            if (listMessages.Items.Count == 0)
            {
                listMessages.Enabled = false;
                fldSender.Enabled = false;
                fldReceiver.Enabled = false;
                fldObject.Enabled = false;
                fldText.Enabled = false;
            }
            else
            {
                foreach (Control c in this.Controls)
                {
                    c.Enabled = true;
                }
            }
        }

        /// <summary>
        /// Fills the receiver field.
        /// </summary>
        /// <param name="receiver">The receivers.</param>
        private void FillReceiver(string[] receiver)
        {
            foreach (string r in receiver)
            {
                fldReceiver.Text += r + ";";
            }
            fldReceiver.Text.Remove(fldReceiver.Text.Length - 1, 1);
        }


        /// <summary>
        /// Clears the fields.
        /// </summary>
        private void Clear()
        {
            fldSender.Text = "";
            fldReceiver.Text = "";
            fldObject.Text = "";
            fldText.Text = ""; ;
        }
        /// <summary>
        /// The subclasses of the LocalizedForm should override this method and use this method to
        /// associate all menu items with custom names with the help of AddMenuToDictionary
        /// method.
        /// </summary>
        protected override void AddMenusToDictionary()
        {
            this.AddMenuToDictionary(this.menuLeft, "menuLeft");
            this.AddMenuToDictionary(this.menuRight, "menuRight");
            this.AddMenuToDictionary(this.menuItemSendNew, "menuItem1");
            this.AddMenuToDictionary(this.menuItemReply, "menuItem2");
            this.AddMenuToDictionary(this.menuItem3, "menuBack");
            this.AddMenuToDictionary(this.menuItem4, "menuHome");
        }
        #endregion;

        #region Response Handling
        /// <summary>
        /// Handles the message response.
        /// </summary>
        /// <param name="e">The MessageResponseEventArgs instance containing the event data.</param>
        private void rrp_MessageResponse(RemoteResourceProvider.MessageResponseEventArgs e)
        {
            stopAnimation();
            try
            {
                if (e.Status == RemoteResourceProvider.okStatus)
                {
                    InitializeInformations(e.Messages);
                }
                else //MessageBox.Show(ResourceManager.Instance.GetString("StatusError"));
                    MessageBox.Show(e.Status);
            }

            catch (ArgumentException ex)
            {
                MessageBox.Show(ResourceManager.Instance.GetString("Exception"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ResourceManager.Instance.GetString("Exception"));
            }
        }

        /// <summary>
        /// Handles the delete response.
        /// </summary>
        /// <param name="e">The BooleanResponseEventArgs instance containing the event data.</param>
        private void rrp_DeleteResponse(RemoteResourceProvider.BooleanResponseEventArgs e)
        {
            if (e.Status == RemoteResourceProvider.okStatus && e.Succeed)
            {
                MessageBox.Show(ResourceManager.Instance.GetString("MessageDeleted"));
            }
            else
            {
                MessageBox.Show(ResourceManager.Instance.GetString("MessageNotDeleted"));
            }
            if (this.listMessages.Items.Count == 0)
            {
                this.menuItemSendNew.Enabled = true;
                this.menuItemReply.Enabled = false;

                listMessages.Enabled = false;
                fldSender.Enabled = false;
                fldReceiver.Enabled = false;
                fldObject.Enabled = false;
                fldText.Enabled = false;
            }
            else {
                this.menuItemSendNew.Enabled = true;
                this.menuItemReply.Enabled = true;
                this.listMessages.SelectedIndex = 0;
            }

            this.stopAnimation();
        }

        /// <summary>
        /// Handles the marked response.
        /// </summary>
        /// <param name="e">The BooleanResponseEventArgs instance containing the event data.</param>
        private void rrp_MarkedResponse(RemoteResourceProvider.BooleanResponseEventArgs e)
        {
            if (!(e.Status == RemoteResourceProvider.okStatus && e.Succeed))
            {
                MessageBox.Show(ResourceManager.Instance.GetString("MessageNotMarked"));
            }
            this.stopAnimation();
        }
        #endregion;

        #region OnPainting
        /// <summary>
        /// Handles the Paint event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.Forms.PaintEventArgs"/> that contains the event data.</param>
        protected override void OnPaint(PaintEventArgs e)
        {
            //Added to prevent painting of "ok" button
            WinAPI.ShowDoneButton(this.Handle, false);
            base.OnPaint(e);
            using (Graphics g = e.Graphics)
            {
                g.DrawImage(Properties.Resources.circles, 3, AutoScrollPosition.Y + 3);
                Point[] p = new Point[]{
                    new Point(40,AutoScrollPosition.Y + 25), 
                    new Point(195,AutoScrollPosition.Y + 25), 
                    new Point(190,AutoScrollPosition.Y + 30), 
                    new Point(40,AutoScrollPosition.Y + 30)};
                using (Brush b = new SolidBrush(Color.Green))
                    g.FillPolygon(b, p);

                p[0].Y = p[1].Y = AutoScrollPosition.Y + 30;
                p[2].Y = p[3].Y = AutoScrollPosition.Y + 35;
                p[1].X -= 10;
                p[2].X -= 10;
                using (Brush b = new SolidBrush(Color.GreenYellow))
                    g.FillPolygon(b, p);
            }
        }
        #endregion;

        #region Event Handling
        /// <summary>
        /// Handles the SelectedIndexChanged event of the listMessages control.
        /// When the user select a message in the list, if it isn't read is marked as read.
        /// Obviously that message is showed in the form.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void listMessages_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = listMessages.SelectedIndex;
            if (index != -1)
            {
                WS_SoapMessage.Message m = messages[index];
                Clear();
                fldSender.Text = m.Sender;
                FillReceiver(m.Receiver);
                fldObject.Text = m.Title;
                string[] temp = m.Text.Split('\n');
                foreach (string t in temp)
                    fldText.Text += t + "\r\n";
                if (!m.IsRead)
                {
                    m.IsRead = true;
                    Welcome.rrp.MarkMessageAsRead(this, rrp_MarkedResponse, m.Id);
                    this.startAnimation();
                }
            }
            menuItemSendNew.Enabled = index != -1;
        }

        /// <summary>
        /// Handles the Click event of the btnDelete control.
        /// Deletes the selected message.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (listMessages.SelectedIndex != -1)
            {
                WS_SoapMessage.Message m = messages[listMessages.SelectedIndex];
                Welcome.rrp.DeleteMessage(this, rrp_DeleteResponse, m.Id);
                Clear();
                int index = listMessages.SelectedIndex;
                listMessages.Items.RemoveAt(index);
                
                
                this.startAnimation();
            }
            else MessageBox.Show(ResourceManager.Instance.GetString("NoMessageSelected"));
        }

        /// <summary>
        /// Handles the Click event of the reply control.
        /// Instance a new ShowSendMessage form to reply to the selected message.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void reply_Click(object sender, EventArgs e)
        {
            //if (listMessages.SelectedIndex != -1)
            //{
            
            WS_SoapMessage.Message m = messages[listMessages.SelectedIndex];
            ShowSendMessage send = new ShowSendMessage(m.Sender, "RE: " + m.Title);
            Welcome.formBuffer.Add(send, "ShowSendMessage");
            send.ShowDialog();
            send.Dispose();
            //}
        }

        /// <summary>
        /// Handles the Click event of the createNew control.
        /// Instance a new ShowSendMessage to create a new message to send.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void createNew_Click(object sender, EventArgs e)
        {
            ShowSendMessage send = new ShowSendMessage();
            Welcome.formBuffer.Add(send, ResourceManager.Instance.GetString("ShowSendMessage"));
            send.ShowDialog();
            send.Dispose();
        }


        /// <summary>
        /// Handles the SelectedIndexChanged event of the comboMessage control.
        /// Used to switch the message showed by the form between Unread Messages and All Messages.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void comboMessage_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboMessage.SelectedIndex;
            switch (index)
            {
                case -1:
                    break;
                case 0:
                    {
                        this.Clear();
                        Welcome.rrp.GetUnreadMessages(this, rrp_MessageResponse);
                        this.startAnimation();
                        break;
                    }
                case 1:
                    {
                        this.Clear();
                        Welcome.rrp.GetReceivedMessages(this, rrp_MessageResponse, 0, 10000);
                        this.startAnimation();
                        break;
                    }
            }
        }

        #endregion;

        #region start/stop animation
        delegate void animationDel();
        /// <summary>
        /// Stops the animation.
        /// </summary>
        private void stopAnimation()
        {
            foreach (Control c in this.Controls)
            {
                c.Enabled = true;
            }
            this.menuLeft.Enabled = true;
            this.menuRight.Enabled = true;
            this.animation.StopAnimation();
            this.AutoScroll = true;
        }
        /// <summary>
        /// Starts the animation.
        /// </summary>
        private void startAnimation()
        {
            foreach (Control c in this.Controls)
            {
                c.Enabled = false;
            }
            this.menuLeft.Enabled = false;
            this.menuRight.Enabled = false;
            this.animation.StartAnimation();
            this.AutoScroll = false;
        }
        #endregion

        /// <summary>
        /// Handles the Click event of the menuItem3(back) control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void menuItem3_Click(object sender, EventArgs e)
        {
            Welcome.formBuffer.Close();
        }

        /// <summary>
        /// Handles the Click event of the menuItem4(back to home) control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The EventArgs instance containing the event data.</param>
        private void menuItem4_Click(object sender, EventArgs e)
        {
            Welcome.formBuffer.Clear();
        }
    }
} 